﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace Milan.Deploy
{
	/// <summary>
	/// Use this class to create a periodic scanner, one that calls its
	/// main thread routine every once in a while.  Override RunOnce
	/// </summary>
	public abstract class PeriodicScanner : ThreadScanner
	{
		public PeriodicScanner(Application application, int interval, int startDelay = 60) : base(application)
		{
			DelayBeforeFirstCheckSeconds = startDelay;
			DelayCheckIntervalSeconds = interval;
		}
		/// <summary>
		/// How many seconds to wait before we first check for an update.
		/// Default: Alpha or Latest = 1 minute
		/// Default: Beta = 1 minute
		/// Default: Official = 1 minute
		/// </summary>
		public int DelayBeforeFirstCheckSeconds { get; set; }
		public int DelayCheckIntervalSeconds = 60*60;
		private ManualResetEvent m_notBusyEvent = new ManualResetEvent(false);
		public ManualResetEvent NotBusy	{ get {	return m_notBusyEvent;	}	}

		/// <summary>
		/// 
		/// </summary>
		protected override void Run()
		{
			QuitEvent.WaitOne(DelayBeforeFirstCheckSeconds * 1000);
			do
			{
				m_notBusyEvent.Reset();
				lock (this)
				{
					RunOnce();
					m_notBusyEvent.Set();
				}
			} while (!QuitEvent.WaitOne(DelayCheckIntervalSeconds * 1000));
		}
		/// <summary>
		/// This calls run once.
		/// </summary>
		protected abstract void RunOnce();
	}
}
